<template>
  <div class="cartcard">
    <div class="item" v-for="item in datas" :key="item.id">
      <van-checkbox v-model="item.checked" @click.native="check(item)"></van-checkbox>
      <van-swipe-cell>
        <van-card
          :num="item.num"
          :price="price_s(item.price,item.discount)"
          :desc="item.select"
          :title="item.gname"
          :thumb="item.img"
          @click.native="detail(item)"
        />
        <template #right>
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            @click.native="deleteItem(item)"
          />
        </template>
      </van-swipe-cell>
    </div>
  </div>
</template>

<script>
export default {
  name: "CartCard",
  data() {
    return {};
  },
  computed: {
    datas() {
      return this.$store.state.cart;
    },
    price_s() {
      return (price, discount) => {
        return (price * discount * 0.1).toFixed(2);
      };
    }
  },
  methods: {
    checkAll() {
      let checkAll = this.datas.every(item => {
        return item.checked == true;
      });
      this.$bus.$emit("checkAll", checkAll);
    },
    check(item) {
      this.$axios({
        url: "/cartcheck",
        method: "post",
        data: {
          checked: !item.checked,
          id: item.id
        }
      }).then(res => {
        this.checkAll()
      });
    },
    deleteItem(item) {
      this.$axios({
        url: "/cartdelete",
        method: "post",
        data: {
          id: item.id
        }
      }).then(res => {
        // this.$store.dispatch("updateCart");
        let checkAll = this.datas.every(item => {
          return item.checked == true;
        });
        this.$bus.$emit("checkAll", checkAll);
      });
    },
    detail(item) {
      this.$router.push({
        path: `/good/${item.good_id}`,
        query: {
          categroy_base_id: item.categroy_base_id
        }
      });
    }
  },
  created(){
    this.checkAll()
  }
};
</script>

<style lang="less" scoped>
.cartcard {
  .item {
    display: flex;
    background-color: #fff;
    padding-left: 5px;
    margin: 5px;

    .van-swipe-cell {
      flex: 1;
      .van-button--danger {
        height: 100%;
      }
    }
  }
}
</style>